<template>
	<view class="search">
		<view class="searchBorder" :class="focus ? 'inputFocus' : ''">
			<text class="uicon-search u-iconfont"></text>
			<input @focus="focus = true" @blur="inputBlur()" v-model="searchValue" placeholder="请输入关键词" />
		</view>

		<view v-if="searchValue&&focus" class="list">
			<m-link :url="web.url" v-for="(web, index) of dataList" :key="index">
				<view class="item" v-if="containStr(web.title, searchValue)">{{ web.title }}</view>
			</m-link>
		</view>
	</view>
</template>

<script>
import data from '@/static/data.js';

export default {
	created() {
		this.dataList = this.changeData(data);
	},
	data() {
		return {
			focus: false,
			searchValue: '',
			dataList: []
		};
	},
	computed: {
		// 传入原串和匹配值
		containStr() {
			return function(str, matchStr) {
				return new RegExp(matchStr, 'i').test(str);
			};
		}
	},
	methods: {
		changeData(webData) {
			let arr = [];
			for (let web of webData) {
				if (web.children) {
					let arrAppend = this.changeData(web.children);
					arr.push(...arrAppend);
				} else {
					arr.push(...web.web);
				}
			}

			return arr;
		},
		inputBlur() {
			setTimeout(() => {
				this.focus = false;
			}, 10);
		}
	}
};
</script>

<style lang="scss" scoped>
.search {
	position: relative;

	.searchBorder {
		display: flex;
		align-items: center;
		border: 1px solid #2c2e2f;
		padding: 6px 8px;
		background-color: #2c2e2f;

		text {
			font-size: 20px;
			color: rgb(160, 148, 146);
		}

		input {
			margin-left: 10px;
			color: #fff;
			line-height: 1;
		}
	}

	.inputFocus {
		border-color: #ffffff;
	}

	.list {
		border: 1px solid #c4c7ce;
		width: 100%;
		position: absolute;
		background-color: #fefefe;
		z-index: 999;
		color: #000;
		.item {
			text-align: left;
			padding: 10px 0;
			padding-left: 40px;
			border-bottom: 1px solid #eeeeee;

			&:hover {
				background-color: #000;
				color: #fefefe;
			}
		}
	}
}
</style>
